//
//  AppDelegate.swift
//  pibar
//
//  Created by apple on 2025/2/27.
//

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    var window: NSWindow!
    var statusItem: NSStatusItem!
    var viewController: ViewController!
    
    // 可选的代币列表
    private let availableTokens: [String: String] = [
        "PI-USDT": "PI Network",
        "DOGE-USDT": "Dogecoin",
        "BTC-USDT": "Bitcoin"
    ]
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        print("Application did finish launching")
        setupWindow() // 先创建 viewController
        setupStatusItem() // 后设置状态栏
        
        // 确保 Touch Bar 支持
        if #available(macOS 10.12.2, *) {
            NSApplication.shared.isAutomaticCustomizeTouchBarMenuItemEnabled = true
        }
        
        // 设置为 accessory 应用
        NSApp.setActivationPolicy(.accessory)
        
        // 隐藏菜单栏和程序坞图标
        NSMenu.setMenuBarVisible(false)
    }
    
    private func setupStatusItem() {
        print("Setting up status item")
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        
        // 设置图标
        if let button = statusItem.button {
            button.image = NSImage(systemSymbolName: "chart.line.uptrend.xyaxis", accessibilityDescription: nil)
            // 添加点击事件
            button.target = self
            button.action = #selector(statusItemClicked)
        }
        
        // 创建菜单
        let menu = NSMenu()
        
        // 添加代币选择项
        for (token, name) in availableTokens {
            let item = NSMenuItem(title: name, action: #selector(toggleToken(_:)), keyEquivalent: "")
            item.representedObject = token
            item.state = viewController.selectedTokens.contains(token) ? .on : .off
            menu.addItem(item)
        }
        
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "退出", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
        
        statusItem.menu = menu
    }
    
    @objc private func toggleToken(_ sender: NSMenuItem) {
        guard let token = sender.representedObject as? String else { return }
        
        if sender.state == .on {
            sender.state = .off
            viewController.removeToken(token)
        } else {
            sender.state = .on
            viewController.addToken(token)
        }
    }
    
    // 添加点击事件处理
    @objc private func statusItemClicked() {
        viewController.reactivateTouchBar()
    }
    
    private func setupWindow() {
        print("Setting up window")
        // 创建视图控制器
        viewController = ViewController()
        
        // 创建窗口
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 300, height: 200),
            styleMask: [.titled, .closable, .miniaturizable],
            backing: .buffered,
            defer: false
        )
        
        window.title = "BTC Price"
        window.contentViewController = viewController
        window.center()
        
        // 设置窗口层级和行为
        window.level = .floating
        window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
        
        // 显示窗口并激活
        window.makeKeyAndOrderFront(nil)
        window.makeFirstResponder(viewController)
        NSApp.activate(ignoringOtherApps: true)
    }
    
    func applicationWillTerminate(_ aNotification: Notification) {
        print("Application will terminate")
        
        // 恢复菜单栏
        NSMenu.setMenuBarVisible(true)
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }
}

